package com.gxuwz.stats.controller;

import com.gxuwz.stats.config.VerifyCode;
import com.gxuwz.stats.entity.User;
import com.gxuwz.stats.security.jwt.JwtTokenUtil;
import com.gxuwz.stats.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.*;


@RestController
@RequestMapping("/auth")
public class LoginController {

    @Autowired
    private LoginService loginService;


    //测试
    @PostMapping("/login")
    public ResponseEntity<Map<String, Object>> login(@RequestBody User loginRequest, HttpSession session) {
        System.out.println();
        // 从 Session 中获取验证码
        String sessionVerifyCode = (String) session.getAttribute("verifyCode");
        System.out.println("Session verifyCode: " + sessionVerifyCode);
        System.out.println("Frontend verifyCode: " + loginRequest.getCode()); // 打印前端传递的验证码

        // 验证码校验逻辑
        if (sessionVerifyCode == null || !sessionVerifyCode.equalsIgnoreCase(loginRequest.getCode())) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "验证码错误");
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(errorResponse);
        }

        // 用户名和密码验证逻辑
        User user = loginService.getByNameAndPassword(loginRequest.getUsername(), loginRequest.getPassword());

        if (user == null) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "用户名或密码错误");
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(errorResponse);
        }

        // 获取用户角色
        String userRole = loginService.getUserRoleByName(user.getUsername());
        System.out.println("角色="+userRole);
// 创建 UserDetails 对象
        UserDetails userDetails = new org.springframework.security.core.userdetails.User(
                user.getUsername(),
                user.getPassword(),
                Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER"))
        );
//        SecurityContextHolder.getContext().setAuthentication(authentication);
        // 创建 Authentication 对象并存储到 SecurityContext
        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                userDetails, // 使用 UserDetails 对象作为 Principal
                null,
                userDetails.getAuthorities()
        );
        SecurityContextHolder.getContext().setAuthentication(authentication);
        int userId = user.getUserId();
        System.out.println("1241322132="+userId);
        // 生成 JWT Token
        JwtTokenUtil jwtTokenUtil = new JwtTokenUtil();
        String token = jwtTokenUtil.generateToken(userDetails, userId);
        // 创建响应数据
        Map<String, Object> responseData = new HashMap<>();
        responseData.put("code", 200);
        responseData.put("msg", "登录成功");
        Map<String, Object> data = new HashMap<>();
        data.put("role", userRole);
        data.put("token", token);
        responseData.put("data", data);

        // 存储用户信息到 Session
        session.setAttribute("user", user);

        return ResponseEntity.ok(responseData);
    }

    @GetMapping("/verify-code")
    public ResponseEntity<Map<String, Object>> getVerifyCode(HttpSession session) throws IOException {
        VerifyCode code = new VerifyCode();
        BufferedImage image = code.createImage();
        // 获取验证码文本
        String verifyCodeText = code.getText();
        System.err.println("Generated verify code: " + verifyCodeText);

        // 将验证码文本存储到 Session 中
        session.setAttribute("verifyCode", verifyCodeText);

        // 构建响应体，包含验证码图片数据
        Map<String, Object> responseBody = new HashMap<>();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(image, "jpg", baos);
        byte[] imageBytes = baos.toByteArray();
        responseBody.put("image", Base64.getEncoder().encodeToString(imageBytes));

        return ResponseEntity.ok(responseBody);
    }


}

